package com.xm.task;

import com.xm.entity.UserP;
import com.xm.util.DataSourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * jdbc(sql手动拼接) 批量插入数据任务
 */
@Slf4j
public class JdbcInsert2Task implements Runnable {
    private final List<UserP> users;
    public JdbcInsert2Task(List<UserP> users) {
        this.users = users;
    }

    @Override
    public void run() {
        if(!CollectionUtils.isEmpty(users)) {
            long start = System.currentTimeMillis();
            //1、注册驱动
            //2、创建数据库连接
            try (Connection conn = DataSourceUtil.getHikariConnection()) {
                //3、开启事务/取消事务自动提交
                conn.setAutoCommit(false);
                //4、执行SQL 获取结果集
                String sql = "INSERT INTO `user` " +
                        "(`uuid`, `name`, `height`, `weight`, `age`, `bool`, `signature`, `delMark`, `createTime`, `updateTime`, `long_field`) " +
                        "VALUES ";
                try (Statement statement = conn.createStatement()) {
                    StringBuilder sqlBuilder = new StringBuilder(sql);
                    for (UserP user : users) {
                        sqlBuilder.append("(");
                        sqlBuilder.append("'").append(user.getUuid()).append("'").append(", ")
                                .append("'").append(user.getName()).append("'").append(",")
                                .append(user.getHeight()).append(",")
                                .append(user.getWeight()).append(",")
                                .append(user.getAge()).append(",")
                                .append(user.getBool() ? 1 : 0).append(",")
                                .append("'").append(user.getSignature()).append("'").append(",")
                                .append(user.getDelMark()).append(",")
                                .append("'").append(user.getCreateTimeStr()).append("'").append(",")
                                .append("'").append(user.getUpdateTimeStr()).append("'").append(",")
                                .append("'").append("Hello jdbc！").append("'")
                        ;
                        sqlBuilder.append("),");
                    }
                    sqlBuilder.deleteCharAt(sqlBuilder.toString().length() - 1);
                    statement.executeUpdate(sqlBuilder.toString());
                    //一次性提交事务
                    conn.commit();
                }
            } catch (SQLException e) {
                //5、关闭连接（try-with-resources 异常或结束后会自动关闭资源）
                log.error("JdbcInsert2Task 批量插入数据异常！e={}", e.getMessage());
                throw new RuntimeException(e);
            } finally {
                int total = users.size();
                long time = System.currentTimeMillis() - start;
                long totalTime = DataSourceUtil.atomicLong.addAndGet(time);
                log.info("JdbcInsert2Task 批量插入{}条数据，耗时{}ms，totalTime={}", total, time, totalTime);
            }
        }
    }

}
